import config from '@/config'
import { createScript } from '@/utils/h5/index'
const MAP_KEY = config.mapKey
import * as utils from '@/utils/h5/index'
import * as auth from '@/utils/auth'
const _getAMap = (resolve) => {
  if (window.AMap) {
    resolve(window.AMap)
    return
  }
  setTimeout(() => {
    _getAMap(resolve)
  }, 100)
}

const GDMap = {
  MAP: null,
  async init() {
    let key = MAP_KEY
    try {
      const data = await auth.getBaseSet()
      key = data.GDMapKey || key
    } catch (error) {
       //
       key = MAP_KEY
    }

    const js = {
      src: `//webapi.amap.com/maps?v=1.4.15&key=${key}&plugin=AMap.Geocoder,AMap.Geolocation`,
      charset: 'utf-8'
    }
    createScript(js).then(() => {
      console.log('高德地图js加载完毕', window.AMap)
    })
  },

  // 获取 Map 对象
  isReady() {
    return new Promise((resolve) => {
      _getAMap(resolve)
    })
  },
  // 生成地图
  mapInit(el, center, options = {}) {
    let _options = {
      zoom: 18,
      resizeEnable: true,
      center
    }
    _options = { ..._options, options }
    return this.isReady().then((MAP) => {
      this.MAP = new MAP.Map(el, _options)
      return this.MAP
    })
  },

  // 添加点
  // content 提示内容
  // className 提示内容的class
  addMarker(lng, lat, content, className) {
    lng = +lng
    lat = +lat
    const marker = new window.AMap.Marker({
      position: [lng, lat]
    })
    this.MAP.add(marker)
    if (content) {
      const infoWindow = this.createInfoWindow(content, className)
      const that = this
      infoWindow.open(that.MAP, marker.getPosition())
    }
  },

  // 创建窗口
  createInfoWindow(content, className) {
    const infoWindow = new window.AMap.InfoWindow({
      // 创建信息窗体
      isCustom: true, // 使用自定义窗体
      content: `<div class="${className}">${content}</div>`, // 信息窗体的内容可以是任意html片段
      offset: new window.AMap.Pixel(0, -35)
    })
    return infoWindow
  },

  // 获取2点之间点距离(米)
  getDistance(lat1, lng1, lat2, lng2) {
    const p1 = [lng1, lat1]
    const p2 = [lng2, lat2]
    return window.AMap.GeometryUtil.distance(p1, p2)
  },

  // 经纬度换城市数据
  async getCityInfo(lng, lat) {
    const AMap = await this.isReady()
    await utils.getWidowValue('Geocoder', AMap)
    var geocoder = new AMap.Geocoder({
      radius: 1000,
      extensions: 'all'
    })
    return new Promise((resolve, reject) => {
      geocoder.getAddress([+lng, +lat], function (status, result) {
        if (status === 'complete' && result.regeocode) {
          var data = result.regeocode
          console.log(result.regeocode)
          resolve(data)
        } else {
          reject({ status, result })
        }
      })
    })
  },

  async geolocation() {
    console.log('我要启动浏览器定位')
    const AMap = await this.isReady()
    await utils.getWidowValue('Geolocation', AMap)
    console.log(AMap.Geolocation, 'Geolocation模块加载完成')
    return new Promise((resolve, reject) => {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位，默认:true
        timeout: 5000 // ，默认：5s
        // buttonPosition:'RB',    //定位按钮的停靠位置
        // buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
      })

      geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
          console.log(result, '浏览器定位result')
          const position = result.position
          resolve({
            lat: position.getLat(),
            lng: position.getLng()
          })
        } else {
          console.log('浏览器定位出错了', status, result)
           reject()
          // const defalutAreaInfo = config.areaInfo
          // const data = {
          //     lat: defalutAreaInfo.lat,
          //     lng: defalutAreaInfo.lng
          // }
          // resolve(data)
        }
      })
    })
  },

  async convertFrom(array, key = 'baidu') {
    console.log('高德坐标系转换')
    const AMap = await this.isReady()
    await utils.getWidowValue('convertFrom', AMap)
    return new Promise((resolve, reject) => {
      AMap.convertFrom(array, key, function (status, result) {
        if (result.info === 'ok') {
          var lnglats = result.locations[0]; // Array.<LngLat>
          console.log(lnglats, '高德坐标系转换成功')
          resolve({
            lat: lnglats.getLat(),
            lng: lnglats.getLng()
          })
        } else {
          console.log('高德坐标系转换失败')
          reject(result)
        }
      })
    })
  },

  convertFromByFuc(fuc, key = 'baidu') {
    return fuc().then(res => {
      const array = [res.lng, res.lat]
      console.log('通过高德转经纬度 ' + key)
      return this.convertFrom(array, key)
    })
  }

}

window.GDMap = GDMap
export default GDMap
